import { Toast } from 'antd-mobile'
import axios from 'axios'
import * as uuid from 'uuid'
axios.defaults.withCredentials = true

const ApiRequest = ({ ...config }): Promise<ResponseDataType> => {
  const {
    api: {
      url = '',
      method = 'POST',
      description = '',
      useElseProxy = false
    },
    params = {},
    headers = undefined,
    successCallback = () => { },
    errorCallback = () => { }
  } = config

  if (!url) {
    return new Promise((resolve, reject) => {
      resolve({
        code: -1,
        data: [],
        note: '[Error] Connot found request url: ' + url,
        total: -1,
      })
    })
  }

  // 这是请求的参数
  let requestParams: any = {
    method, // 请求方法，默认 POST
    url: !useElseProxy ? '/api' + url : url, // 请求链接
    headers: Object.assign({ 'Content-Type': 'application/json' }, headers ? {
      ...headers,
    } : {
      "Accept": 'application/json',
      'Content-Type': 'application/json;charset=utf-8',
      'x-request-uuid': uuid.v4(),
    }),
    cerdentials: 'include',
    // data: params, // 请求参数
    timeout: 20000, // 最大延迟 20s,
    timeoutErrorMessage: '连接超时，请稍后再试！', // 超时消息提示
    // mode: 'cors', // 是否跨域
  }

  if (method === 'GET') {
    requestParams.params = params
  } else {
    requestParams.data = params
  }

  return new Promise<ResponseDataType>((resolve, reject) => {
    axios(requestParams).then((response: any) => {
      resolve(response.data)
      successCallback(response)
    }).catch((error: any) => {
      reject({ message: '请求失败', error: error.code + ': ' + error.message })
      errorCallback(error)
    })
  })
}

export default ApiRequest
